package com.wujie.mall.domain.order;

import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单聚合根
 * 
 * @author wujie
 * @since 2024-08-26
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Order {

    /**
     * 订单ID
     */
    private Long id;

    /**
     * 订单号
     */
    private String orderNo;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 订单状态
     */
    private OrderStatus status;

    /**
     * 订单总金额
     */
    private BigDecimal totalAmount;

    /**
     * 实付金额
     */
    private BigDecimal payAmount;

    /**
     * 运费
     */
    private BigDecimal freight;

    /**
     * 优惠金额
     */
    private BigDecimal discountAmount;

    /**
     * 订单项列表
     */
    @Builder.Default
    private List<OrderItem> items = new ArrayList<>();

    /**
     * 收货地址
     */
    private ShippingAddress shippingAddress;

    /**
     * 订单备注
     */
    private String remark;

    /**
     * 支付方式
     */
    private String paymentMethod;

    /**
     * 支付时间
     */
    private LocalDateTime paymentTime;

    /**
     * 发货时间
     */
    private LocalDateTime deliveryTime;

    /**
     * 完成时间
     */
    private LocalDateTime completeTime;

    /**
     * 取消时间
     */
    private LocalDateTime cancelTime;

    /**
     * 创建时间
     */
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    private LocalDateTime updatedAt;

    /**
     * 添加订单项
     * @param item 订单项
     */
    public void addItem(OrderItem item) {
        if (items == null) {
            items = new ArrayList<>();
        }
        items.add(item);
        recalculateAmount();
    }

    /**
     * 移除订单项
     * @param item 订单项
     */
    public void removeItem(OrderItem item) {
        if (items != null) {
            items.remove(item);
            recalculateAmount();
        }
    }

    /**
     * 重新计算订单金额
     */
    public void recalculateAmount() {
        if (items == null || items.isEmpty()) {
            totalAmount = BigDecimal.ZERO;
            return;
        }

        totalAmount = items.stream()
                .map(OrderItem::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 计算实付金额 = 总金额 + 运费 - 优惠金额
        payAmount = totalAmount
                .add(freight != null ? freight : BigDecimal.ZERO)
                .subtract(discountAmount != null ? discountAmount : BigDecimal.ZERO);
    }

    /**
     * 获取订单项数量
     * @return 订单项数量
     */
    public int getItemCount() {
        return items != null ? items.size() : 0;
    }

    /**
     * 获取商品总数量
     * @return 商品总数量
     */
    public int getTotalQuantity() {
        if (items == null) {
            return 0;
        }
        return items.stream()
                .mapToInt(OrderItem::getQuantity)
                .sum();
    }

    /**
     * 检查订单是否可以支付
     * @return true-可以支付，false-不可以支付
     */
    public boolean canPay() {
        return status == OrderStatus.PENDING_PAYMENT && 
               payAmount != null && 
               payAmount.compareTo(BigDecimal.ZERO) > 0;
    }

    /**
     * 检查订单是否可以取消
     * @return true-可以取消，false-不可以取消
     */
    public boolean canCancel() {
        return status == OrderStatus.PENDING_PAYMENT || 
               status == OrderStatus.PAID;
    }

    /**
     * 验证订单完整性
     * @throws IllegalStateException 订单信息不完整时抛出
     */
    public void validate() {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            throw new IllegalStateException("订单号不能为空");
        }
        
        if (userId == null) {
            throw new IllegalStateException("用户ID不能为空");
        }
        
        if (items == null || items.isEmpty()) {
            throw new IllegalStateException("订单项不能为空");
        }
        
        if (shippingAddress == null) {
            throw new IllegalStateException("收货地址不能为空");
        }
        
        if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalStateException("订单总金额必须大于0");
        }
        
        // 验证每个订单项
        for (OrderItem item : items) {
            item.validate();
        }
        
        // 验证收货地址
        shippingAddress.validate();
    }
}